import React, { Component } from 'react'
import { Button, StyleSheet, View } from 'react-native'
import { inject, observer } from 'mobx-react/native'
import { graphql, withApollo } from 'react-apollo'
import gql from 'graphql-tag'

import { Modal } from 'antd-mobile'
import { Icon, RegisterForm } from '../components'
import { variables } from '../styles'

const REGISTER_MUTATION = gql`
  mutation(
    $username: String!
    $password: String!
    $name: String
    $role: String!
  ) {
    register(
      username: $username
      password: $password
      name: $name
      role: $role
    ) {
      token
      userId
    }
  }
`

const USER_QUERY = gql`
  query {
    user {
      id
      username
      name
      role
    }
  }
`

@inject('actions', 'store')
@observer
@withApollo
@graphql(REGISTER_MUTATION, { name: 'register' })
export class RegisterScreen extends Component {
  register = async values => {
    try {
      const { actions, register, client, navigation, store } = this.props

      const response = await register({
        variables: { ...values, role: 'CUSTOMER' },
      })

      actions.login(response.data.register)

      const { data: { user } } = await client.query({ query: USER_QUERY })

      store.user = user

      navigation.replace('Main')
    } catch (error) {
      Modal.alert('Error', String(error))
      console.warn('TODO', error)
    }
  }

  render = () => (
    <View style={styles.container}>
      <View style={styles.logo}>
        <Icon
          size={90}
          name="radio-button-off"
          color={variables.color_icon_base}
        />
      </View>
      <RegisterForm onSubmit={this.register} />
      <Button
        title="Go to Login"
        onPress={() => this.props.navigation.replace('Login')}
      />
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: 'white',
  },
  logo: {
    alignItems: 'center',
    marginBottom: variables.v_spacing_xl,
  },
})
